簡體   English   中英

單擊父級LinearLayout時如何獲取子級TextView的值?

[英]How to get the value of a child TextView when a parent LinearLayout is clicked?

我要添加任意數量的包含單個TextViews的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);
}

我希望能夠獲得TextView的值,該值是剛剛被單擊的LinearLayout的子級,我該怎么做?

您可以嘗試這樣的方法,在您的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();
    }
}

嘗試這個 :

TextView tv = textWrapper.findViewById(//TextView Id);
tv.getText().toString();

如果您只有一個孩子,請按照以下步驟進行操作:

   TextView tv = (TextView) textWrapper.getChildAt(0);
   String text = tv.getText().toString();

或多次使用Spirrow答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM