[英]How to change the background color of a view from a different activity in android?
我正在开发一个测验应用程序。 First when a user opens the app they go to the MainActivity
, from there when they press start they go to the Categories Activity, from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions活动,最后在完成所有问题后,他们到达分数活动。 在得分活动中,当单击完成按钮时,它们将被重定向到MainActivity
。 在得分活动中,我想将他们完成的 Set 的颜色更改为绿色而不是默认颜色。 我怎样才能做到这一点? 我创建了一个集合项目布局 xml 文件,并使用适配器在 Sets Activity 中使用来自适配器的视图填充gridview
。 目前,单击 ScoreActivity 中的“完成”按钮后,我得到了 null object 参考。
这是代码:
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
@Override
public int getCount() {
return numOfSets;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
由于您的活动序列是MainActivity
-> Categories
-> Sets
-> Scores
。
您有两个选项来更改颜色,具有两个不同的生命周期的更改。
要临时更改颜色,这将在关闭应用程序或重新启动“Sets”活动后自行重置。 可以通过两种方式完成:使用公共 Static 变量和使用公共 function。
永久更改颜色,直到应用程序被卸载/重新安装。 您应该使用SharedPreferences
。 SharedPreferences
就像存储在设备的 memory 中以供进一步使用的私有数据一样,并且除非应用程序被删除/数据被清除,否则它会保持不变。 虽然,具有 root 权限的应用程序可以访问任何应用程序的SharedPreferences
数据,也可以对其进行修改。
您可以按照此处的说明使用SharedPreferences
。 或者,您可以使用一些库以一种简单的方式访问它。 我在所有应用程序中使用它的方式是TinyDB (它只是一个 java/kotlin 文件)。 这可以作为:
//store the value from ScoreActivity after completion as TinyDB tinyDB = TinyDB(this); tinyDB.putBoolean("isSet1Completed",true); //access the boolean variable in SetsActivity to change the color of any set that //is completed and if it's true, just change the color. TinyDB tinyDB = TinyDB(this); Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
但是,您喜欢哪种方式是您的选择。 现在,这是关于您将要进行的更改的生命周期:临时或永久。 现在,我们将讨论如何更改颜色。
在Sets
活动中使用公共 static 变量。 您可以做的是您可以将要更改其背景的 imageView/textview 设置为公共 static 变量。 请记住,这个想法不是首选,因为它会导致 memory 泄漏,但这很容易。
将其声明为public static ImageView imageview;
(或TextView
)在onCreated()
中将其初始化为imageView = finViewById(R.id.viewId);
在Sets
活动中。
将其称为new SetsActivity().imageView.setBackgroundColor(yourColor);
在ScoreActivity
中。
第二种方法是在 SetsAcitvity 中创建一个公共的SetsAcitvity
,将颜色更改代码放入其中,然后从ScoreActivity
中调用它。 只需将其声明为public void changeColor(){ //your work}
并从ScoreActivity
其称为new SetsActivity().changeCOlor()
。 您还可以像setId
一样将一些 arguments 传递给 function 。
我已经为你提供了你需要的一切。 Rest 你应该弄清楚自己要真正学习它而不是复制它。
我认为您只需在 MainActivity 中添加标志。
例如,在 MainActivity 中添加标志。
boolean isFromDone = false;
完成点击后,
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
在 MainActivity 中添加这个。
@Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
假设您在活动 A 中有一个线性布局,并且您想通过单击活动 B 中的按钮来更改它的背景颜色。
Step 1
创建 class 并声明 static 变量。
class Util { private static LinearLayout mylayout ; }
Step 2
在持有此布局的活动中,对其进行初始化。
Util.mylayout = findviewbyid(R.id.linear);
Step 3
从活动 B 更改按钮单击的背景颜色
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.