单击父LinearLayout时如何获取子TextView的值?

crm*_*ham 1 android android-layout onclicklistener

我正在添加包含单个TextView的任意数量的LinearLayouts.

LinearLayout l = (LinearLayout) findViewById(R.id.contacts_container);
for (int i = 0; i < array.length(); i++) {
    JSONObject object = array.getJSONObject(i);
    String username = object.getString("username");

    // add linearLayout text wrapper to main wrapper
    LinearLayout textWrapper = new LinearLayout(getApplicationContext());
    textWrapper.setOrientation(LinearLayout.VERTICAL);
    textWrapper.setBackgroundResource(R.drawable.orangeborder);
    textWrapper.setPadding(0, 0, 0, 0);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    textWrapper.setLayoutParams(params);
    textWrapper.setId(userId);
    textWrapper.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // when this linearlayout is clicked
            // get the value of this child textview with an id of R.id.contactUsername
            // start new intent and pass the username

            //TextView tv_id = (TextView) ((View) v.getParent()).findViewById(R.id.contact);
            Intent intent = new Intent(ContactsActivity.this, ProfileActivity.class);
            intent.putExtra("username", "this username");
            startActivity(intent);
        }
    });
    l.addView(textWrapper);

    // add username TextView to textWrapper
    TextView usernameText = new TextView(getApplicationContext());
    lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    usernameText.setLayoutParams(lp);
    usernameText.setId(R.id.contactUsername);
    usernameText.setText(fullName);
    usernameText.setTextColor(Color.parseColor("#FFFFFF"));
    usernameText.setTextSize(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
    textWrapper.addView(usernameText);
}
Run Code Online (Sandbox Code Playgroud)

我希望能够获得TextView的值,该TextView是刚刚被点击的LinearLayout的子项,我该怎么做?

Spi*_*row 5

你可以尝试这样的东西,在你的onClick()中调用它

for(int i=0; i<((ViewGroup)v).getChildCount(); ++i) {
    View nextChild = ((ViewGroup)v).getChildAt(i);
    if(nextChild.getId() == R.id.your_id){
    String text = ((TextView) nextChild).getText().toString();
    }
}
Run Code Online (Sandbox Code Playgroud)