I'm working on an app where I made a "custom keyboard" of sorts where you can "type in" playing cards. I made that "keyboard" a fragment and I am trying to make it appear on my main activity but it won't show up. I've looked everywhere but can't find a solution. As you can probably tell, I'm pretty new to android and especially fragments. Any help would be appreciated.
Code:
MainActivity.java:
package com.example.cribbage2;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements
CardKeyboardFrag.CardTransfer{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment newFragment = new Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onCardSelected(int card) {
//do stuff with int here
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.cribbage2.MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="368dp"
android:layout_height="495dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent">
</FrameLayout>
CardKeyboardFrag.java
package com.example.cribbage2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class CardKeyboardFrag extends android.support.v4.app.Fragment implements View.OnClickListener {
CardTransfer mCallback;
public interface CardTransfer {
void onCardSelected(int card);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.card_keyboard_frag, container, false);
//region buttonAssignments
Button one = (Button) getView().findViewById(R.id.buttonA);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(1);
}
});
Button two = (Button) getView().findViewById(R.id.button2);
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(2);
}
});
Button three = (Button) getView().findViewById(R.id.button3);
three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(3);
}
});
Button four = (Button) getView().findViewById(R.id.button4);
four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(4);
}
});
Button five = (Button) getView().findViewById(R.id.button5);
five.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(5);
}
});
Button six = (Button) getView().findViewById(R.id.button6);
six.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(6);
}
});
Button seven = (Button) getView().findViewById(R.id.button7);
seven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(7);
}
});
Button eight = (Button) getView().findViewById(R.id.button8);
eight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(8);
}
});
Button nine = (Button) getView().findViewById(R.id.button9);
nine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(9);
}
});
Button ten = (Button) getView().findViewById(R.id.button10);
ten.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(10);
}
});
Button eleven = (Button) getView().findViewById(R.id.buttonJ);
eleven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(11);
}
});
Button twelve = (Button) getView().findViewById(R.id.buttonQ);
twelve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(12);
}
});
Button thirteen = (Button) getView().findViewById(R.id.buttonK);
thirteen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(13);
}
});
Button delete = (Button) getView().findViewById(R.id.buttonD);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(14);
}
});
Button buttonGo = (Button) getView().findViewById(R.id.buttonG);
buttonGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
buttonClicked(15);
}
});
//endregion
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallback = (CardTransfer) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement CardTransfer");
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
buttonClicked(1);
break;
case R.id.button2:
buttonClicked(2);
break;
case R.id.button3:
buttonClicked(3);
break;
case R.id.button4:
buttonClicked(4);
break;
case R.id.button5:
buttonClicked(5);
break;
case R.id.button6:
buttonClicked(6);
break;
case R.id.button7:
buttonClicked(7);
break;
case R.id.button8:
buttonClicked(8);
break;
case R.id.button9:
buttonClicked(9);
break;
case R.id.button10:
buttonClicked(10);
break;
case R.id.buttonJ:
buttonClicked(11);
break;
case R.id.buttonQ:
buttonClicked(12);
break;
case R.id.buttonK:
buttonClicked(13);
break;
case R.id.buttonD:
buttonClicked(14);
break;
case R.id.buttonG:
buttonClicked(15);
break;
}
}
public void buttonClicked(int num){
mCallback.onCardSelected(num);
}
}
card_keyboard_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Cards"
android:textAlignment="center"
android:textSize="30sp"/>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="8dp"
android:columnCount="3"
android:rowCount="5">
<Button
android:id="#+id/buttonK"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="King"/>
<Button
android:id="#+id/buttonD"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="Delete"/>
<Button
android:id="#+id/buttonG"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="Go!"/>
<Button
android:id="#+id/button10"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="10"/>
<Button
android:id="#+id/buttonJ"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="Jack"/>
<Button
android:id="#+id/buttonQ"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="Queen"/>
<Button
android:id="#+id/button7"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="7"/>
<Button
android:id="#+id/button8"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="8"/>
<Button
android:id="#+id/button9"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="9"/>
<Button
android:id="#+id/button4"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="4"/>
<Button
android:id="#+id/button5"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="5"/>
<Button
android:id="#+id/button6"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="6"/>
<Button
android:id="#+id/buttonA"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="Ace"/>
<Button
android:id="#+id/button2"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="2"/>
<Button
android:id="#+id/button3"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="3"/>
</GridLayout>
</RelativeLayout>
Thanks again in advance!
You have to create an instance of your fragment - not only a generic fragment.
Like:
CardKeyboardFrag cardFrag = new CardKeyboardFrag();
and
transaction.add(R.id.fragment_container, cardFrag);
Related
I think is happening in the switch case or there is any small error in my code.
Please help me out
Here is my code:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/edText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="180sp"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="230sp"
android:text="1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="170sp"
android:layout_marginTop="230sp"
android:text="2"/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="280sp"
android:layout_marginTop="230sp"
android:text="3"/>
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="280sp"
android:text="4" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="170sp"
android:layout_marginTop="280sp"
android:text="5"/>
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="280sp"
android:layout_marginTop="280sp"
android:text="6"/>
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="330sp"
android:text="7" />
<Button
android:id="#+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="170sp"
android:layout_marginTop="330sp"
android:text="8"/>
<Button
android:id="#+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="280sp"
android:layout_marginTop="330sp"
android:text="9"/>
<Button
android:id="#+id/buttonplus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="380sp"
android:text="+" />
<Button
android:id="#+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="170sp"
android:layout_marginTop="380sp"
android:text="0"/>
<Button
android:id="#+id/buttoneq"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="280sp"
android:layout_marginTop="380sp"
android:text="="/>
<Button
android:id="#+id/buttondiv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="430sp"
android:text="/" />
<Button
android:id="#+id/buttonmin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="170sp"
android:layout_marginTop="430sp"
android:text="-"/>
<Button
android:id="#+id/buttonmul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="280sp"
android:layout_marginTop="430sp"
android:text="*"/>
</RelativeLayout>
MainActivity.java:
package com.example.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
int operator = 0;
int s1 = 0,s2 = 0,add = 0,min = 0,mul = 0,div = 0;
EditText tv;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,beq,bplus,bmin,bmul,bdiv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
b2 = (Button)findViewById(R.id.button2);
b3 = (Button)findViewById(R.id.button3);
b4 = (Button)findViewById(R.id.button4);
b5 = (Button)findViewById(R.id.button5);
b6 = (Button)findViewById(R.id.button6);
b7 = (Button)findViewById(R.id.button7);
b8 = (Button)findViewById(R.id.button8);
b9 = (Button)findViewById(R.id.button9);
b0 = (Button)findViewById(R.id.button0);
beq = (Button)findViewById(R.id.buttoneq);
bplus = (Button)findViewById(R.id.buttonplus);
bmin = (Button)findViewById(R.id.buttonmin);
bmul = (Button)findViewById(R.id.buttonmul);
bdiv = (Button)findViewById(R.id.buttondiv);
tv = (EditText) findViewById(R.id.edText);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "1");
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "2");
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "3");
}
});
b4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "4");
}
});
b5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "5");
}
});
b6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "6");
}
});
b7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "7");
}
});
b8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "8");
}
});
b9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(tv.getText() + "9");
}
});
b0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText( tv.getText() + "0");
}
});
bplus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = Integer.parseInt(tv.getText().toString());
tv.setText(null);
operator = 1;
}
});
bmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = Integer.parseInt(tv.getText().toString());
tv.setText(null);
operator = 2;
}
});
bmul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = Integer.parseInt(tv.getText().toString());
tv.setText(null);
operator = 3;
}
});
bdiv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = Integer.parseInt(tv.getText().toString());
tv.setText(null);
operator = 4;
}
});
beq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s2 = Integer.parseInt(tv.getText().toString());
add = s1 + s2;
min = s1 - s2;
mul = s1 * s2;
div = s1 / s2;
switch (operator){
case 1:
tv.setText(add);
break;
case 2:
tv.setText(min);
break;
case 3:
tv.setText(mul);
break;
case 4:
tv.setText(div);
break;
}
}
});
}
}
I have added 15 buttons to my calculator and everything works properly except when I click on equal to the button. Every button does works properly and prints the proper number into the textView when clicked but still when I click on the equal to button, my app just shuts down itself whenever I click on the equal to button on my calculator and nothing happens.
It seems like you need to parse integers to strings before you set the text. Try using String.valueOf() to parse add, min, mul, and div to strings.
Also, if you post your logcat, it'll be much easier to figure out what the problem is as it tells you what and where the error is.
You can not set integer value on Textview, only String will be acceptable. Try with the below code.
switch (operator){
case 1:
tv.setText(""+add);
break;
case 2:
tv.setText(""+min);
break;
case 3:
tv.setText(""+mul);
break;
case 4:
tv.setText(""+div);
break;
}
if you give an int value to setText(), it will be seen as a resId,so ,if system can not find this id, will throw new NotFoundException("String resource ID #0x"
+ Integer.toHexString(id));
Change eq listener to
beq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(tv.getText().toString().length()==0)
return;
s2 = Integer.parseInt(tv.getText().toString());
add = s1 + s2;
min = s1 - s2;
mul = s1 * s2;
div = s1 / s2;
switch (operator) {
case 1:
tv.setText(String.valueOf(add));
break;
case 2:
tv.setText(String.valueOf(min));
break;
case 3:
tv.setText(String.valueOf(mul));
break;
case 4:
tv.setText(String.valueOf(div));
break;
}
}
});
Do not set integer value to text view directly. First cast it to string.
Try replacing this in your code.
I have one activity and three fragments. In fragment(1), i have a chronometer that works perfectly. Firstly, i click chronometer start button. When chronometer shows 00:10, i open fragment(2). Then i return after 6 seconds, chronometer shows 00:00. I want it to show 00:16 and keep working while i changing fragments.
Fragment (1) xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Chronometer
android:id="#+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:textSize="70dp"
android:textColor="#fff"
/>
<Button
android:id="#+id/btn_Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_below="#+id/chronometer"
android:background="#drawable/btn_bg"
android:textColor="#fff"
/>
<Button
android:id="#+id/btn_Pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause"
android:layout_centerHorizontal="true"
android:layout_below="#+id/btn_Start"
android:background="#drawable/btn_bg"
android:layout_marginTop="20dp"
android:textColor="#fff"/>
<Button
android:id="#+id/btn_Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:layout_centerHorizontal="true"
android:layout_below="#+id/btn_Pause"
android:background="#drawable/btn_bg"
android:layout_marginTop="20dp"
android:textColor="#fff"/>
<Button
android:id="#+id/btn_Back"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/btn_Reset"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="0dp"
android:background="#drawable/btn_bg_2"
android:drawableRight="#drawable/ic_fast_rewind_black_24dp"
android:textColor="#fff" />
<Button
android:id="#+id/btn_Forward"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/btn_Reset"
android:layout_alignParentRight="true"
android:layout_marginRight="30dp"
android:background="#drawable/btn_bg_2"
android:drawableLeft="#drawable/ic_fast_forward_black_24dp"
android:textColor="#fff" />
</RelativeLayout>
This is my fragment(1) java code.
public class HomeFragment extends Fragment {
private Button btn_start;
private Button btn_pause;
private Button btn_reset;
private Button btn_back;
private Button btn_forward;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_home, container, false);
chronometer = view.findViewById(R.id.chronometer);
chronometer.setFormat("%s");
btn_forward= view.findViewById(R.id.btn_Forward);
btn_back = view.findViewById(R.id.btn_Back);
btn_start= view.findViewById(R.id.btn_Start);
btn_pause= view.findViewById(R.id.btn_Pause);
btn_reset= view.findViewById(R.id.btn_Reset);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
backChronometer();
}
});
btn_forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
forwardChronometer();
}
});
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startChronometer();
}
});
btn_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pauseChronometer();
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pauseChronometer();
resetChronometer();
}
});
return view;
}
}
This is chronometer java code. (methods)
public class Chronometer {
public static long pauseOffset;
public static boolean running;
public static void startChronometer (){
if(!running){
chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
chronometer.start();
running = true;
}
}
public static void pauseChronometer (){
if (running){
pauseOffset = SystemClock.elapsedRealtime() - chronometer.getBase();
chronometer.stop();
running = false;
}
}
public static void resetChronometer (){
chronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
}
public static void forwardChronometer (){
if (running) {
chronometer.setBase(chronometer.getBase()-1000);
}
}
public static void backChronometer (){
if (running) {
chronometer.setBase(chronometer.getBase()+1000);
}
}
}
MainActivity java code.
public class MainActivity extends AppCompatActivity {
public static Chronometer chronometer;
public static TextView tv_rune;
public static SeekBar sb_rune;
public static int minrune = 0, maxrune = 35, currentrune;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame,
new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem
menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.navigation_info:
selectedFragment = new InfoFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame,
selectedFragment).commit();
return true;
}
};
}
Also I want to keep seekbar datas from fragment(2) to use them in fragment (1).
Actually, I wonder how can we keep data protected.
Try using setRetainInstance(true) in onCreate of the fragment, as described here.
https://stackoverflow.com/a/22884377/5343907
Maybe this suits your needs.
Android: How to restore the state of a stopped chronometer after rotation?
So I have made a simple heating text control app and it all works with permissions and all of that but it uses 2 fragments and inside them are two textboxes which I want to have the same text in -- phone number. I cannot get the edittext in rel2 to be changed by rel1.
Rel 1:
package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.SmsManager;
import static android.content.SharedPreferences.*;
/**
* Created by Daniel Kern on 03/01/2018.
*/
public class Rel1 extends Fragment{
Button BtnHOFF, BtnHON, BtnHST, saveB;
EditText txtPhoneNo;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rel1, container, false);
final View view2 = inflater.inflate(R.layout.rel2, container, false);
final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
String savedNo = sharedPref.getString("phoneNo", "07599070551");
BtnHOFF = (Button) view.findViewById(R.id.Hoff);
BtnHON = (Button) view.findViewById(R.id.Hon);
BtnHST = (Button) view.findViewById(R.id.Hstatus);
txtPhoneNo = (EditText) view.findViewById(R.id.editText);
saveB = (Button) view.findViewById(R.id.saveB);
((EditText) view.findViewById(R.id.editText)).setText(savedNo);
Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
BtnHOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL1=ON", txtPhoneNo.getText().toString());
}
});
BtnHON.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL1=OFF", txtPhoneNo.getText().toString());
Log.i(getActivity().toString(), "Done!");
}
});
BtnHST.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#STATUS", txtPhoneNo.getText().toString());
}
});
saveB.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
Log.i("me", "Saved!");
Toast.makeText(getActivity().getApplicationContext(),
"Saved!",
Toast.LENGTH_LONG).show();
((EditText) view2.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
}
});
return view;
}
public void sendMsg(String msg, String num){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, msg, null, null);
Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(),
"SMS failed, contact administrator!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
}
}
Rel 2:
package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Daniel Kern on 03/01/2018.
*/
public class Rel2 extends Fragment {
Button BtnWOFF, BtnWON, BtnWST, saveB;
EditText txtPhoneNo;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rel2, container, false);
final View view1 = inflater.inflate(R.layout.rel1, container, false);
final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
String savedNo = sharedPref.getString("phoneNo", "07599070551");
BtnWOFF = (Button) view.findViewById(R.id.Woff);
BtnWON = (Button) view.findViewById(R.id.Won);
BtnWST = (Button) view.findViewById(R.id.Wstatus);
saveB = (Button) view.findViewById(R.id.saveB);
txtPhoneNo = (EditText) view.findViewById(R.id.editText);
((EditText) view.findViewById(R.id.editText)).setText(savedNo);
Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
BtnWOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL2=ON", txtPhoneNo.getText().toString());
}
});
BtnWON.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL2=OFF", txtPhoneNo.getText().toString());
}
});
BtnWST.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#STATUS", txtPhoneNo.getText().toString());
}
});
saveB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
((EditText) view1.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
Log.d("me", "Saved!");
}
});
return view;
}
public void sendMsg(String msg, String num){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, msg, null, null);
Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(),
"SMS failed, contact administrator!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
}
}
Rel 1 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/Hon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:text="Heating ON (REL1 OFF)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Hoff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Hon"
android:layout_marginTop="13dp"
android:text="Heating OFF (REL1 ON)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Hstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Hoff"
android:layout_marginTop="15dp"
android:text="STATUS"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texts"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="Coming Soon!"
android:textSize="24sp" />
<EditText
android:id="#+id/editText"
android:text="07599070551"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/saveB"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/editText"
android:layout_alignBottom="#+id/editText"
android:layout_alignParentEnd="true"
android:text="Save" />
</RelativeLayout>
Rel 2 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/Won"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:text="Water ON (REL2 OFF)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Woff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Won"
android:layout_marginTop="13dp"
android:text="Water OFF (Rel2 On)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Wstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Woff"
android:layout_marginTop="15dp"
android:text="STATUS"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texts"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="Coming Soon!"
android:textSize="24sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/saveB"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/editText"
android:layout_alignBottom="#+id/editText"
android:layout_alignParentEnd="true"
android:text="Save" />
</RelativeLayout>
EDIT:
I would like the edit text in Rel2 to change when I press save in rel1 therefore the phone number boxes will always be the same.
rel1
EDIT 2:
I have fixed the shared prefs issue but I would still like to know if anyone can make the textboxes the same wherether that is on text update or on save button press.
There are two ways you can do this.
Using Interface
Create an interface with a method something like TextChangeListener and declare a method onTextChange(String text).
interface TextChangeListener{
void onTextChange(String number);
}
Implement the interface in the HostActivity
class HostActivity extends Activity implements TextChangeListener{
...
void onTextChange(String number){
secondFragment.updateNumber(number)
}
...
}
In FirstFragment call the activity using the implmented interface in the afterTextChanged() listener of TextWatcher
class FirstFragment extends Fragment{
private TextChangeListener activity;
#Override
public onAttach(Context context){
if(context instanceof TextChangeListener){
activity = (TextChangeListener) context;
}
}
phNumEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
activity.onTextChange(s.toString);
}
...
);
...
}
In SecondFragment on receiving the call from activity, update the EditText with new data.
class SecondFragment extends Fragment{
...
public void updateNumber(String number){
editText.setText(number);
}
}
Using EventBus
Use EventBus to post an event from FirstFragment. The event will contain the data to be populated in SecondFragment. The SecondFragment will Subscribe to the event and on receiving the event the data will be populate into the EditText.
After much research, I have been unable to figure out how I can initialize my TextView in my java file in Android Studio. The TextView in question is located in a different layout file so I don't know the correct syntax to use. I think my question is similar to: Null pointer Exception on .setOnClickListener
But the solution for him is not working for me.
Here is my troublesome code:
Microsoft = (Button) findViewById(R.id.Microsoft);
Microsoft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
//TextView score = (TextView) findViewById(R.id.score);
TextView score = (TextView)
score.findViewById(R.id.question2);
(score).setText(0);
}
});
TheFindViewById part is the part I need.
FULL CODE VVVV
package org.flinthill.finalprojectv3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.text.method.DigitsKeyListener;
import android.text.InputFilter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SuSe;
Button DOS;
Button B;
Button BIOS;
Button Microsoft;
Button LenBosackandSandyLerner;
Button HaskelDiklah;
Button SteveWozniak;
SuSe = (Button) findViewById(R.id.SuSe);
SuSe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText(0);
}
});
DOS = (Button) findViewById(R.id.DOS);
DOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText("0");
}
});
B = (Button) findViewById(R.id.B);
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText("0");
}
});
BIOS = (Button) findViewById(R.id.BIOS);
BIOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Right!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText("1");
setContentView(R.layout.question2);
}
});
//QUESTION 2
Microsoft = (Button) findViewById(R.id.Microsoft);
Microsoft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
//TextView score = (TextView) findViewById(R.id.score);
TextView score = (TextView)
score.findViewById(R.id.question2);
(score).setText(0);
}
});
/*LenBosackandSandyLerner = (Button)
findViewById(R.id.LenBosackandSandyLerner);
LenBosackandSandyLerner.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Right!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText("2");
setContentView(R.layout.question3);
}
});
HaskelDiklah = (Button) findViewById(R.id.HaskelDiklah);
HaskelDiklah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText("0");
}
});
SteveWozniak = (Button) findViewById(R.id.SteveWozniak);
SteveWozniak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Wrong!",
Toast.LENGTH_SHORT).show();
TextView score = (TextView) findViewById(R.id.score);
(score).setText("0");
}
});*/
}
}
XML CODE:
LAYOUT 1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/android"
tools:context="org.flinthill.finalprojectv3.MainActivity">
<TextView
android:layout_width="wrap_content"
android:id="#+id/LUL"
android:textColor="#color/LightGreen"
android:layout_height="wrap_content"
android:typeface="serif"
android:text="Which is NOT an OS?"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:textSize="24sp"/>
<Button
android:id="#+id/SuSe"
android:onClick="SuSeClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SuSe"
android:layout_marginTop="100dp"
android:layout_below="#+id/LUL"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/BIOS"
android:onClick="BIOSClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BIOS"
android:layout_below="#+id/SuSe"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/DOS"
android:onClick="DOSClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOS"
android:layout_below="#+id/BIOS"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/B"
android:onClick="BClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B"
android:layout_below="#+id/DOS"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/score"
android:textColor="#color/colorAccent"
android:text="0"
android:textSize="32dp"
android:layout_below="#+id/LUL"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
LAYOUT 2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/question2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/android"
tools:context="org.flinthill.finalprojectv3.MainActivity">
<TextView
android:layout_width="wrap_content"
android:id="#+id/question2text"
android:textColor="#color/LightGreen"
android:layout_height="wrap_content"
android:typeface="serif"
android:text="Who created Cisco"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:textSize="24sp"/>
<Button
android:id="#+id/Microsoft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Microsoft"
android:layout_marginTop="100dp"
android:layout_below="#+id/question2text"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/LenBosackandSandyLerner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Len Bosack and Sandy Lerner"
android:layout_below="#+id/Microsoft"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/HaskelDiklah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Haskel Diklah"
android:layout_below="#+id/LenBosackandSandyLerner"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/SteveWozniak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Steve Wozniak"
android:layout_below="#+id/HaskelDiklah"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/score"
android:textColor="#color/colorAccent"
android:text="1"
android:textSize="32dp"
android:layout_below="#+id/question2text"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
//Change the name id in the xml file
Button microsoftButton = (Button) findViewById(R.id.microsoftButton);
TextView scoreTextView = (TextView) findViewById(R.id.scoreTextView);
microsoftButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Wrong!", Toast.LENGTH_SHORT).show();
// This was declared above so now you can use it. You can only set it to a String not to an Integer.
scoreTextView.setText("0");
}
});
You cannot do this unless your TextView is within the layout your Activity, Fragment or Dialog controls.
The findViewById method looks for Views within the layout previously configured by the setContentView(layout) or the layout inflated in your Fragment or Dialog. If it does not find anything, your TextView will have a null reference.
I'm making a wallpaper app similar in functionality to Google's new wallpaper app. There is a Horizontal Scroll View at the bottom with a list of Image Buttons that when clicked will show a preview of the wallpaper in the app. How do I tell the app to set the wallpaper from the one being previewed?
My xml:
<RelativeLayout
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:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:clickable="true"
tools:context="biz.bigtooth.wallpapers.MainActivity">
<Button
android:id="#+id/set"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:padding="16dp"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:background="#color/button"
android:gravity="start|center_vertical"
android:textColor="#android:color/white"
android:text="Set Wallpaper" />
<HorizontalScrollView
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#color/bottom">
<ImageButton android:id="#+id/dsc18"
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_margin="8dp"
android:focusable="true"
android:src="#drawable/_dsc0018" />
<ImageButton android:id="#+id/dsc65"
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_margin="8dp"
android:focusable="true"
android:src="#drawable/_dsc0065" />
<ImageButton android:id="#+id/dsc131"
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_margin="8dp"
android:focusable="true"
android:src="#drawable/_dsc0131" />
<ImageButton android:id="#+id/dsc175"
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_margin="8dp"
android:focusable="true"
android:src="#drawable/_dsc0175" />
<ImageButton android:id="#+id/dsc246"
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_margin="8dp"
android:focusable="true"
android:src="#drawable/_dsc0246" />
<ImageButton android:id="#+id/dsc274"
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_margin="8dp"
android:focusable="true"
android:src="#drawable/_dsc0274" />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
My Java:
import android.app.WallpaperManager;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.FocusFinder;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
RelativeLayout layout;
HorizontalScrollView view;
Button set;
ImageButton dsc18;
ImageButton dsc65;
ImageButton dsc131;
ImageButton dsc175;
ImageButton dsc246;
ImageButton dsc274;
int oneeight = R.drawable._dsc0018pr;
int sixfive = R.drawable._dsc0065pr;
int onethreeone = R.drawable._dsc0131pr;
int onesevenfive = R.drawable._dsc0175pr;
int twofoursix = R.drawable._dsc0246pr;
int twosevenfour = R.drawable._dsc0274pr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (RelativeLayout)findViewById(R.id.layout_main);
layout.setBackgroundResource(oneeight);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(view.isShown()
? View.GONE
: View.VISIBLE );
}
});
view = (HorizontalScrollView)findViewById(R.id.view);
set = (Button)findViewById(R.id.set);
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWallpaper(onesevenfive);
}
});
dsc18 = (ImageButton)findViewById(R.id.dsc18);
dsc65 = (ImageButton)findViewById(R.id.dsc65);
dsc131 = (ImageButton)findViewById(R.id.dsc131);
dsc175 = (ImageButton)findViewById(R.id.dsc175);
dsc246 = (ImageButton)findViewById(R.id.dsc246);
dsc274 = (ImageButton)findViewById(R.id.dsc274);
dsc18.hasFocus();
dsc18.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundResource(oneeight);
dsc18.hasFocus();
}
});
dsc65.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundResource(sixfive);
dsc65.hasFocus();
}
});
dsc131.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundResource(onethreeone);
dsc131.hasFocus();
}
});
dsc175.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundResource(onesevenfive);
dsc175.hasFocus();
}
});
dsc246.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundResource(twofoursix);
dsc246.hasFocus();
}
});
dsc274.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundResource(twosevenfour);
dsc274.hasFocus();
}
});
}
public void setWallpaper(int id) {
int wall = getBackground;
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(wall);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks for any and all help in advance!
First , you need to set the required permission
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
and then :
dsc18.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(onethreeone);
} catch (IOException e) {
e.printStackTrace();
}
dsc18.hasFocus();
}
});