【问题标题】:How to access all children of linearLayout? [duplicate]如何访问linearLayout的所有孩子? [复制]
【发布时间】:2018-11-19 06:02:02
【问题描述】:

我在线性布局中有图像视图。当单击其父级(线性布局)时,我试图获取所有图像视图(子级)。您能否告诉我单击线性布局时如何访问线性布局的所有子级?

【问题讨论】:

  • 请详细说明您想要达到的目标。
  • 看起来您在询问之前没有搜索过,而您必须这样做。

标签: java android android-studio android-layout imageview


【解决方案1】:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:id="@+id/linerLayout"
    >

   <ImageView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/imageView"
       android:src="@drawable/ic_launcher_background"
       />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textId"
        />

</LinearLayout>

MainActivity.java

package com.example.macchhindra.stackoverflowexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
 LinearLayout linearLayout;
 TextView myTextView;
 ImageView myImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout = (LinearLayout) findViewById(R.id.linerLayout);
        myTextView = (TextView) findViewById(R.id.textId);
        myImageView = (ImageView) findViewById(R.id.imageView);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /// change your Image view image in this section
            }
        });
    }
}

【讨论】:

    【解决方案2】:

    试试这个代码..

           LinearLayout ll =findViewById(R.id.linear);
        final int childCount = ll.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View v = ll.getChildAt(i);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2020-08-05
      • 2019-10-14
      相关资源
      最近更新 更多