gpt4 book ai didi

android - 在 Android 中根据条件隐藏和显示布局

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:56 25 4
gpt4 key购买 nike

我是 Android 新手。我想根据 if else 条件隐藏和显示 Linearlayout。在我的应用程序中,我使用了 1 个微调器。根据选定的微调器值,我希望我的下一个布局隐藏或可见,但如果它一旦消失,它就不会再次可见。

我的代码是:

    public class Expense extends Activity{
Spinner datype;

public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.expense);
mainlayout=(LinearLayout)this.findViewById(R.id.layout1);
datype=(Spinner)findViewById(R.id.da_type);
List<String>data1=new ArrayList<String>();
data1.add("Local");
data1.add("Ex-Station Double Side");
data1.add("Ex-Station Single Side");
data1.add("Out-Station Double Side");
data1.add("Out-Station Single Side");
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,data1);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
datype.setAdapter(adapter);
if(datype.getSelectedItem().toString().equals("Local")){

mainlayout.setVisibility(LinearLayout.GONE);
}
else
mainlayout.setVisibility(LinearLayout.VISIBLE);


}

}

最佳答案

您需要设置 OnItemSelectedListener 并更改那里的布局。以下是您的 Activity 实现 OnItemSelectedListener 的示例。

public class Expense extends Activity implements OnItemSelectedListener {

private Spinner datype;
private LinearLayout mainlayout;

public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.expense);
mainlayout=(LinearLayout)this.findViewById(R.id.layout1);
datype=(Spinner)findViewById(R.id.da_type);
List<String>data1=new ArrayList<String>();
data1.add("Local");
data1.add("Ex-Station Double Side");
data1.add("Ex-Station Single Side");
data1.add("Out-Station Double Side");
data1.add("Out-Station Single Side");
ArrayAdapter<String>adapter=new ArrayAdapter<String (this,android.R.layout.simple_spinner_item,data1);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
datype.setAdapter(adapter);
if(datype.getSelectedItem().toString().equals("Local")){
mainlayout.setVisibility(LinearLayout.GONE);
}
else {
mainlayout.setVisibility(LinearLayout.VISIBLE);
}

// here we set the listener
datatype.setOnItemSelectedListener(this);
}

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// here we change layout visibility again
if(datype.getSelectedItem().toString().equals("Local")){
mainlayout.setVisibility(LinearLayout.GONE);
}
else {
mainlayout.setVisibility(LinearLayout.VISIBLE);
}
}

public void onNothingSelected(AdapterView<?> parent) {
}
}

关于android - 在 Android 中根据条件隐藏和显示布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18545222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com