Programmatically create a resource identifier for submission

Viewcontains a method setId(int). My question is how to programmatically put an Id object that does not overlap the resource identifier in R?

+3
source share
2 answers

According to the document , View.generateViewId()added to 17 API level, will be generated value suitable for use setId(int). This value will not interfere with the ID values ​​generated at build time using aapt for R.id.

I experimented with View.generateViewId()to find out how he behaves. Here are my findings.

  • 1 (1, 2, 3...)
  • generateViewId() , . , 4, 5.

, , , onCreate() , generateViewId() , , , onCreate() , .

Android - , , EditText, CheckBox - , , . , - EditText , , , - , . , .

, Android , XML, . , , : 2131427423. , , generateViewId(). , , 1, , . , :

public class MainActivity extends AppCompatActivity {
    // since our lastAllocatedViewId will reset on device rotation
    // regenerated views will receive the same ID
    private int lastAllocatedViewId = 0;

    private ArrayList<QuizQuestions> quizQuestions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // read quizQuestions from xml at runtime;
        quizQuestions = parseQuizQuestionsXml();

        // we will dynamically add quiz question views to this view
        // depending on how many quizQuestions are in the XML config
        LinearLayout container = (LinearLayout) findViewById(R.id.quiz_questions_container);

        // generate a view for each quiz question
        for (int i = 0; i < quizQuestions.size(); i++) {
            LinearLayout quizQuestionView = (LinearLayout) inflater.inflate(R.layout.quiz_question_template, parent, false);

            quizQuestionView.setId(lastAllocatedViewId++);

            (...) // do some work on our newly generated view

            // then add it to the quiz questions container
            container.addView(quizQuestionView);
        }
    }
}
+2

Android View.setId()

-1

All Articles