How to include same layout twice programmatically in android? - java

i have trouble to call layout programmatically, i try in xml using include and its work
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/btnTes"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/LL1"
android:orientation="vertical">
<include layout="#layout/extend">
</include>
<include layout="#layout/extend">
</include>
</LinearLayout>
but i want create it programmatically
this is my extend XML :
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<TextView
android:text="TextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2" />
and this is my java :
public class MainActivity extends AppCompatActivity {
Button btnTes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup tes = (ViewGroup) findViewById(R.id.LL1);
btnTes = (Button) findViewById(R.id.btnTes);
final View extend = LayoutInflater.from(this).inflate(R.layout.extend,null);
btnTes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "KLIk", Toast.LENGTH_SHORT).show();
tes.addView(extend);
}
});
}
}
when i click btnTes
for the first clicked its ok, but when i click it again my program just force close. This is my error
FATAL EXCEPTION: main
Process: com.example.siwonhansamu.test, PID: 3796
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Thanks

You can't add the same view to multiple parents.
You have to do a copy of the view if you want it multiple times. You could do like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup tes = (ViewGroup) findViewById(R.id.LL1);
btnTes = (Button) findViewById(R.id.btnTes);
btnTes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "KLIk", Toast.LENGTH_SHORT).show();
final View extend = LayoutInflater.from(view.getContext()).inflate(R.layout.extend, tes, false);
tes.addView(extend);
}
});
}

when i click btnTes for the first clicked its ok, but when i click it
again my program just force close.
that's the expected behavior. A View's instace can have only one parent. When you press the button for the second time extend has already a parent (tes), and you cannot call addView again on that instance. The quick fix is to move
final View extend = LayoutInflater.from(this).inflate(R.layout.extend,null);
into onClick. This way, every time you press on the Button, a new instance is created.

Related

Can't dismiss a popup window (other solutions do not work)

I am trying to create a simple PopupWindow with a text entry field.
I know there are many questions of this type, but none seem to solve my problem. This is the XML of my popup layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:background="#color/white"
android:gravity="center"
android:padding="15dp"
android:layout_gravity="center"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dodaj produkt po identyfikatorze"
android:textSize="15sp"
android:gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:textSize="20sp"
android:hint="Identyfikator"
android:minWidth="250dp"
android:id="#+id/insert_edit"
android:gravity="center"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:id="#+id/insert_ok"
android:text="OK"/>
<Button
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:id="#+id/insert_cancel"
android:text="Anuluj"/>
</LinearLayout>
</LinearLayout>
Now, I want to create this layout in my main activity when a FAB is pressed. This is how I do it:
public class ScrollingActivity extends AppCompatActivity {
private ActivityScrollingBinding binding;
private int ACTIVITY_LOAD_DATABASE = 1;
AbstractDatabase database;
RowAdapter rowAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = Room.databaseBuilder(getApplicationContext(), AbstractDatabase.class, "magazyn_db")
.allowMainThreadQueries().build();
binding = ActivityScrollingBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
FloatingActionButton fab = binding.addCode;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.println(Log.INFO, "VIEWs", "Showing popup");
PopupWindow codePopup;
View popupView = getLayoutInflater().inflate(R.layout.insert_code, binding.getRoot());
codePopup = new PopupWindow(popupView);
codePopup.setFocusable(true);
codePopup.setOutsideTouchable(true);
View cancelButton = codePopup.getContentView().findViewById(R.id.insert_cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
codePopup.dismiss();
}
});
View acceptButton = codePopup.getContentView().findViewById(R.id.insert_ok);
acceptButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View editView = codePopup.getContentView().findViewById(R.id.insert_edit);
String id = ((EditText)editView).getText().toString().trim();
insertNewElement(id);
codePopup.dismiss();
}
});
}
});
[...]
For an unknown reason my popup doesn't go dismissed, both when I click outside of it, or press the cancel button (when I tried to print some logs from the handler, they worked). I have tried many solutions, also inflating it with no root, but then 'showAtPosition' doesn't even show it, and no solutions here on stackoverflow seem to help me even though there are many of them.
Is anyone able to point the problem here?
public void dismiss () Disposes of the popup window. This method can be invoked only after showAsDropDown(android.view.View) has been executed. Failing that, calling this method will have no effect.

Why SetText not work in OnClick() function

I just know how to use Android Studio Code Yesterday. And I got a problem when I need to Change the text when clicking a button.
But when I text, Its don't work.
Here is my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View bubbleView = getLayoutInflater().inflate(R.layout.bubble_view, null);
Button bubble = (Button) findViewById(R.id.start_bubble);
bubble.setOnClickListener(this);// calling onClick() method
Button predict = (Button) bubbleView.findViewById(R.id.predict);
predict.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_bubble:
startService(new Intent(getApplicationContext(), SimpleService.class));
case R.id.predict:
View bubbleView = getLayoutInflater().inflate(R.layout.bubble_view, null);
TextView predict_text = (TextView) bubbleView.findViewById(R.id.predict_text);
predict_text.setText("Hi"); // <--- It don't work :(
default:
break;
}
}
}
[EDIT] []
Add some .XML file
Here is my activity_main.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.siddharthks.sampleapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Project KHKT"
android:textColor="#AA000000"
android:textSize="21sp" />
<Button
android:id="#+id/start_bubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Paste and Predict"
android:textSize="18sp" />
</LinearLayout>
and here is my bubble_view.xml, its just for a
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:paddingEnd="16dp"
android:text="Project KHKT"
android:textColor="#AA000000"
android:textSize="21sp" />
<Button
android:id="#+id/predict"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Paste and Predict"
android:textSize="18sp" />
<TextView
android:id="#+id/predict_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:paddingEnd="16dp"
android:textColor="#AA000000"
android:textSize="21sp" />
</LinearLayout>
</ScrollView>
Do you have any suggested for me ?
I'm not sure why you inflate the "bubble_view.xml" layout in the activity class. But as your question, there are two main methods to make the button clickable. There is a good explanation in your first comment which is done by Mike M. Once you inflate a layout, it will create a new instance.
Fist answer, Assuming you want everything inside the activity.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button bubble;
private Button predict;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUIViews() // Initialze UI Views
initUIActions() // Initialize Ui Actions
}
private void initUiViews() {
Button bubble = (Button) findViewById(R.id.start_bubble);
Button predict = (Button) bubbleView.findViewById(R.id.predict);
}
private void initUIActions() {
bubble.setOnClickListener(this);// calling onClick() method
predict.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_bubble:
startService(new Intent(getApplicationContext(), SimpleService.class));
break;
case R.id.predict:
predict_text.setText("Hi");
break;
default:
break;
}
}
}
and restructure your XML layout as follow. There are few ways to restructure these layouts, I'll write the easiest way, but note that this is not the optimal way.
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.siddharthks.sampleapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Project KHKT"
android:textColor="#AA000000"
android:textSize="21sp" />
<Button
android:id="#+id/start_bubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Paste and Predict"
android:textSize="18sp" />
<!-- include bubble layout file -->
<include layout="#layout/bubble_view.xml" />
</LinearLayout>
Other than the include tag you can add the whole code inside to the Activity layout.
The second answer, Assuming you want activity and Service with a bubble view.
If you are looking for a bubble view, You have to create a Bubble service.
Check this answer: Bubble Example
Official Doc: Android Bubble
Try This it will add Your bubble view in your parent and you can perform any action on that particular Layout from main Layout.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout parent = findViewById(R.id.activity_main); //parent layout.
View childView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bubble_view,parent,false);
parent.addView(childView);
Button predict = (Button) childView.findViewById(R.id.predict);
TextView predict_text = (TextView) childView.findViewById(R.id.predict_text);
predict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
predict_text.setText("Hi"); // <--- It don't work :(
}
});
}
}
Add break to the each case statement in the switch.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView predict_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) findViewById(R.id.start_bubble);
LinearLayout parent = findViewById(R.id.activity_main);
View childView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bubble_view, parent, false);
parent.addView(childView);
Button predict = (Button) childView.findViewById(R.id.predict);
predict_text = (TextView) childView.findViewById(R.id.predict_text);
predict.setOnClickListener(this);
start.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.predict:
predict_text.setText("Hi");
break;
}
}
}

Android Studio My Button on the second Activity doesn't Work

I think it a very easy Question. I am new to Android Studio and I could not find an answer.
I have an activity that switches per Button to another activity. However, on my second activity, my simple Button just to change the Textview which doesn't work.
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StartActivity">
<TextView
android:id="#+id/twText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="127dp"
android:layout_marginLeft="127dp"
android:layout_marginTop="88dp"
android:layout_marginEnd="127dp"
android:layout_marginRight="127dp"
android:layout_marginBottom="624dp"
android:text="Ihr Passwort war Richtig!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnChecke"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="189dp"
android:layout_marginRight="189dp"
android:layout_marginBottom="371dp"
android:text="Check"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
onCreate method in my second activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tw = findViewById(R.id.twText);
btnCheck = findViewById(R.id.btnChecke);
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("work");
}
});
}
And this is how I am starting the second activity (onCreate method from my first activity).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tw = findViewById(R.id.twText);
Button btnCheck = findViewById(R.id.btnChecke);
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView("Work"R.layout.activity_main);
}
});
}
I have checked the variable names in the layout and looks like everything is fine.
Thank you in advance.
This answer is based on the problem which I found before the latest edit from the OP. Here is the version of the edit where I found the problem.
First of all, something is very wrong about the onClickListener of your button. You are setting the content view again, instead of starting your second activity. It looks like, you are just setting the content view of your StartActivity which actually does not launch the MainActivity that you are trying to start.
In order to start a new activity, you need to add the following in your button onClickListener.
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// setContentView(R.layout.activity_main); // This is not the way for starting another activity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
});
Once your MainActivity has started, you should be able to change the text with no problem.
Bundle bundle = getIntent().getExtras()
if(bundle.getString("changeTextView")
TextView .... = (TextView) ....setText();
Hi. If I good understand, you should use Intent with "putExtra()".
Exmple:intent.putExtras("changeTextView");
After that in your onCreate() method you can put:

Method findViewById not working as I expected [duplicate]

This question already has answers here:
findViewByID returns null
(33 answers)
Closed 3 years ago.
I'm trying to change the text of a NavigationView's child. I am using findViewById to get directly to the TextView. It works in the MainActivity, but in every other Activity findViewById returns a null reference.
By the way this is my first submitted question and I hope I respected the guidelines.
I can't seem to figure this out so I don't know where to start.
This is the NavigationView located in the layout of every activity
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:visibility="visible"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"/>
nav_header_main is the component that has the said TextView, it is referenced in the code above. This is nav_header_main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_header"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:id="#+id/nav_header_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Angheluta Filip"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#android:color/white" />
</LinearLayout>
This code is from MainActivity, where finding the said text view doesn't return a null reference
NavigationManager navigationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Downloads the database and than proceeds to setup the Activity
//onDataChange gets called when the download is finished and dataSnapshot is the downloaded
//data
final AppCompatActivity context = this;
FirebaseHandler.getFirebaseHandler().getReference().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
FirebaseHandler.getFirebaseHandler().setData(dataSnapshot);
DataSnapshot userSnapshot = dataSnapshot.child("Users").child(FirebaseHandler.getFirebaseHandler().getAuth().getUid());
User.initializeCurrentUser(userSnapshot);
//Add side bar to this activity
navigationManager = new NavigationManager(context);
navigationManager.createNavBar();
//Recycler view setup
RecyclerManager recyclerManager = new RecyclerManager();
recyclerManager.createRecyclerWithLargeElements(context, Voluntariat.getDataSet());
//Sort spinner setup
SortSpinnerManager sortSpinnerManager = new SortSpinnerManager();
sortSpinnerManager.createSortSpinnerManager(context, recyclerManager);
//Search bar setup
SearchBarManager searchBarManager = new SearchBarManager();
searchBarManager.createSearchBar(context, recyclerManager, Voluntariat.getDataSet());
TextView textViewHeader = findViewById(R.id.nav_header_textView);
Log.d("textHeader", textViewHeader.getText().toString());
textViewHeader.setText(User.currentUser.lastName + " " + User.currentUser.firstName);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
But this is from any other Activity in the onCreate method
RecyclerManager recyclerManager;
NavigationManager navigationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toate_vol);
//Add side bar to this activity
navigationManager = new NavigationManager(this);
navigationManager.createNavBar();
//RECYCLERVIEW SETUP
recyclerManager = new RecyclerManager();
recyclerManager.createRecyclerWithSmallElements(this, Voluntariat.getDataSet());
//Search bar managing
SearchBarManager searchBarManager = new SearchBarManager();
searchBarManager.createSearchBar(this, recyclerManager, Voluntariat.getDataSet());
TextView textViewHeader = findViewById(R.id.nav_header_textView);
Log.d("textHeader", textViewHeader.getText().toString());
textViewHeader.setText(User.currentUser.lastName + " " + User.currentUser.firstName);
}
When I access any activity other than the MainActivity I get NullPointerException on the textViewHeader.
EDIT: I added more code and i changed it so the findViewById is called straight from the Activity file rather than from the NavigationManager file. The error is the same.
EDIT2: Added some more code from activity_toate_vol.xml:
It seems like this layout doesn't have any view with the problematic id, but the id is located in the nav_header_main.xml file which is set in the activity_toate_vol.xml file with the headerLayout attribute:
app:headerLayout="#layout/nav_header_main"
This NavigationView is a direct child of the root layout and the rest of the code is irrelevant, This same navigation view is found in the MainActivity as well.
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:visibility="visible"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:gravity="bottom"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgdeconctare"
android:layout_width="27dp"
android:layout_height="27dp"
android:alpha=".6"
android:src="#drawable/ic_logout"
app:srcCompat="#drawable/ic_logout"
tools:srcCompat="#drawable/ic_logout" />
<TextView
android:id="#+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:gravity="center|start"
android:text="Deconectare"
android:textColor="#android:color/black" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.NavigationView>
EDIT 3: I came out with a workaround and also identified the problem. Turns out I have to somehow wait for that NavigationView to inflate before I update it's text. Can anyone help me with the proper way to do this? Cause I am not happy with this.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
wait(150);
}
catch(Exception e){
}
TextView textViewHeader = findViewById(R.id.nav_header_textView);
Log.d("textHeader", textViewHeader.getText().toString());
textViewHeader.setText(User.currentUser.lastName + " " + User.currentUser.firstName);
}
}, 100);
Welcome! When findViewById returns null, that can mean 2 things.
1) The layout that you pass to 'setContentView' does not have a view with that id...
2) The layout does have that view, but the view itself is not fully inflated yet. To wait until a view is fully inflated, you can use a GlobalLayoutListener
in java:
setContentView(R.layout.activity_other);
final NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
TextView text = navigationView.findViewById(R.id.nav_header_textView);
text.setText("Hello StackOverflow");
navigationView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
and when you switch to kotlin:
setContentView(R.layout.activity_main)
val view = findViewById<NavigationView>(R.id.nav_view)
view?.viewTreeObserver?.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener{
override fun onGlobalLayout() {
val header = findViewById<TextView>(R.id.nav_header_textView)
header.text= "Hallo Main"
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})

How to make one ImageView invisible when another clickable ImageView is pressed?

I tried to make ImageView(bul1) disappear when ImageView(Seethrough) is pressed. I get a nullpointer error when i try to run this code. What is wrong with it?
JAVA code
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView seethrough1 = (ImageView) findViewById(R.id.Seethrough);
final ImageView view1 = (ImageView) findViewById(R.id.bul1);
seethrough1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(view1.getVisibility() == View.VISIBLE)
{
view1.setVisibility(View.INVISIBLE);
}
}
});
}
XML code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:paddingBottom="6dp"
android:src="#drawable/gun"
android:clickable="true"
android:id="#+id/Seethrough"
android:onClick="next"
/>
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/bullet"
android:id="#+id/bul1"
/>
</LinearLayout>
You need to reconcile seethrough's onClickListener with its onClick XML attribute. I'd suggest removing this line from the xml:
android:onClick="next"
and placing the code inside your next method (if you have one)
public void next (View v){
some code
}
behind or before your visibility checking if, whichever suits you more:
#Override
public void onClick(View v) {
//place some code here
if(view1.getVisibility() == View.VISIBLE){
view1.setVisibility(View.INVISIBLE);
}
//or here
}
I think their is problem with out xml code, please try writing xml as follows,
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:paddingBottom="6dp"
android:src="#drawable/gun"
android:clickable="true"
android:id="#+id/Seethrough"
android:onClick="next"
/>
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/bullet"
android:id="#+id/bul1"
/>
</LinearLayout>
If it return NullPointerExeption, I think your ImageView is Null, because
setContentView(R.layout.activity_main);
and activity_main.xml is not like contents of your post, check name of layout and try again.
I found out that I was supposed to declare the imageviews inside the method instead of before.
like this
public void onClick(View v) {
ImageView seethrough1 = (ImageView) findViewById(R.id.Seethrough);

Categories