How do I set a wallpaper based on the Image selected? - java

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();
}
});

Related

I want to make a search bar for this code to search by buttons (between btn1 and btn2 and btn3) and hide the non-matched results

I am trying to add a search bar that enables me to search by buttons, search between btn1 and btn2 and btn3. I tried a lot of codes but all of them were focused on TextView and not on buttons. So hope to help me and if I missed details please let me know to describe more.
The two files (.java and .xml) are typed below. thank you.
file.java
package com.example.myapp1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
SearchView sv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("My First App");
Button btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}});
Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity3.class);
startActivity(intent);
}});
Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity4.class);
startActivity(intent);
}});
List<Button> buttonList = new ArrayList<>();
buttonList.add(view.findViewById(R.id.btn1));
buttonList.add(view.findViewById(R.id.btn2));
buttonList.add(view.findViewById(R.id.btn3));
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
for(int i = 0; i < buttonList.size(); i++) {
String buttonText = (String) buttonList.get(i).getText();
if(buttonText.toLowerCase(Locale.ROOT).equals(s.toLowerCase())) {
buttonList.get(i).setVisibility(View.VISIBLE);
} else {
buttonList.get(i).setVisibility(View.INVISIBLE);
}
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s.isEmpty()) {
for(int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.VISIBLE);
}
}
return false;
}
});
}
}
file.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity"
tools:ignore="ExtraText"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginHorizontal="10dp"
android:orientation="vertical"
android:weightSum="2">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Absolute Pressure" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Acoustic Flowmeter" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/btn3"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Bernoulli Number" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
What do you mean by search by buttons? Are you looking to search the text that is held within the button?
Here is a way you can go about this:
Make a list that contains all the instances of your buttons.
List(findViewById(R.id.btn1), etc)
List<Button> buttonList = new ArrayList<>();
buttonList.add(view.findViewById(R.id.button_search1));
buttonList.add(view.findViewById(R.id.button_search2));
buttonList.add(view.findViewById(R.id.button_search3));
We are going to use the listeners available to the search view to do the work.
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// You can use this for when the submit is clicked
#Override
public boolean onQueryTextSubmit(String s) {
// We loop over the button list
for(int i = 0; i < buttonList.size(); i++) {
// We get the text of the button
String buttonText = (String) buttonList.get(i).getText();
// We turn both the button text and search result to lowercase
// So that results are not case sensitive
// If they match
if(buttonText.toLowerCase(Locale.ROOT).equals(s.toLowerCase())) {
// We make button visible
buttonList.get(i).setVisibility(View.VISIBLE);
} else {
// If it doesn't, we make invisible
buttonList.get(i).setVisibility(View.INVISIBLE);
}
}
return false;
}
// You can use this when the text is changing.
#Override
public boolean onQueryTextChange(String s) {
// If text is empty, reset results
if(s.isEmpty()) {
for(int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.VISIBLE);
}
}
return false;
}
});

Android Fragments - Edit Text Of Another Fragment

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.

Fragment Not Appearing

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);

code for image run in arraylist

i do array list with images thet i want them to run with 2 buttons thet go next pic and beck pic i dont know the code for this i thx all for the time you spend for help.
ackage com.example.hanansanag.mytourneyccreator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
/**
* Created by ssh on 25/12/2016.
*/
public class Players extends AppCompatActivity implements View.OnClickListener {
protected Button btnNext, btnBack;
protected String fname;
protected String Lname;
protected String team;
protected ImageView iv;
protected ArrayList array_image;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.team_pic);
ArrayList<Integer> array_image = new ArrayList<Integer>();
array_image.add(R.drawable.bacelona);
array_image.add(R.drawable.athlethiko);
array_image.add(R.drawable.arsenak);
array_image.add(R.drawable.chelsea);
array_image.add(R.drawable.dortmond);
array_image.add(R.drawable.city);
array_image.add(R.drawable.bayernunchen);
array_image.add(R.drawable.intermilan);
array_image.add(R.drawable.psj);
array_image.add(R.drawable.realmadrid);
array_image.add(R.drawable.leverpool);
array_image.add(R.drawable.milan);
array_image.add(R.drawable.juventus);
array_image.add(R.drawable.ashkelon);
array_image.add(R.drawable.macabiheifa);
array_image.add(R.drawable.macabitelaviv);
array_image.add(R.drawable.beitaryeroshlaim);
array_image.add(R.drawable.apoelbersheva);
iv = (ImageView) findViewById(R.id.imageView);
btnNext = (Button) findViewById(R.id.btnNextPic);
btnBack = (Button) findViewById(R.id.btnBeckPic);
btnBack.setOnClickListener(this);
btnNext.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (i <= 0 || i >= array_image.length) {
return;
}
if (btnNext == v) {
iv.setImageResource(array_image.get(i++));
} else if (btnBack == v) {
iv.setBackgroundResource(array_image.get(i--));
}
}
}
**what can i do here in this line of code thet the pic will move : **
#Override
public void onClick(View v) {
if (i <= 0 || i >= array_image.length) {
return;
}
if (btnNext == v) {
iv.setImageResource(array_image.get(i++));
} else if (btnBack == v) {
iv.setBackgroundResource(array_image.get(i--));
}
}
this is the 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"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/teamimage">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:text="Fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="12dp"
android:id="#+id/textView2" />
<ImageView
android:layout_height="80dp"
android:id="#+id/imageView"
android:layout_width="80dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:text="Lname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:id="#+id/Lname"
android:layout_below="#+id/textView2"
android:layout_toEndOf="#+id/imageView" />
<TextView
android:text="Fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="12dp"
android:id="#+id/textView3" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true">
<Button
android:layout_width="20dp"
android:layout_height="15dp"
android:id="#+id/btnBeckPic"
android:background="#drawable/btnbeck"
android:layout_marginStart="30dp"
android:layout_alignBottom="#+id/Lname"
android:layout_toEndOf="#+id/textView2" />
<Button
android:background="#drawable/btnnext"
android:layout_width="20dp"
android:layout_height="15dp"
android:id="#+id/btnNextPic"
android:layout_below="#+id/imageView"
android:layout_toEndOf="#+id/btnBeckPic"
android:layout_marginStart="14dp" />
</GridLayout>
</RelativeLayout>
int currentImage = 0;
String[] strArr = new String[array_image.size()];
strArr = array_image.toArray(stockArr);
#Override
public void onClick(View v) {
if (btnNext == v) {
currentImage++;
currentImage = currentImage % strArr .length;
iv.setImageResource(strArr .length[currentImage]);
} else if (btnBack == v) {
currentImage--;
currentImage = (currentImage + strArr .length) % strArr .length;
iv.setImageResource(strArr[currentImage]);
}
}

Inflated layout's buttons onClick listener not working

All my other onClick methods work except the ones in which I have to inflate the layout to get the button! What am I doing wrong! Here is some code:
package com.games.think;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TableLayout;
public class Think extends Activity{
//What question are we on?
int question = 1;
//What level are we on?
String lvl ="1";
//Radio buttons we need to access them global
RadioButton lvl1;
RadioButton lvl2;
RadioButton lvl3;
RadioButton lvl4;
RadioButton lvl5;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//play
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
playOnClick(v);
}
});
//level
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
levelOnClick(v);
}
});
//setLevel
LayoutInflater inflater = LayoutInflater.from(this);
TableLayout tbl = new TableLayout(this);
View playv = inflater.inflate(R.layout.level, null);
Button updateLevel = (Button) playv.findViewById(R.id.updateLevel);
tbl.addView(updateLevel);
updateLevel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateLevelOnClick(v);
}
});
View levelv = inflater.inflate(R.layout.play, null);
Button gotomenu = (Button) levelv.findViewById(R.id.tomenu);
gotomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toMenuOnClick(v);
}
});
//Radio Buttons
lvl1 = (RadioButton) levelv.findViewById(R.id.lvl1);
lvl2 = (RadioButton) levelv.findViewById(R.id.lvl2);
lvl3 = (RadioButton) levelv.findViewById(R.id.lvl3);
lvl4 = (RadioButton) levelv.findViewById(R.id.lvl4);
lvl5 = (RadioButton) levelv.findViewById(R.id.lvl5);
//tomenu
lvl = getLevel();
if(lvl.equals("-1")) {
lvl=getLevel();
}
}
protected void toMenuOnClick(View v) {
setContentView(R.layout.main);
}
protected void updateLevelOnClick(View v) {
setContentView(R.layout.main);
}
protected void levelOnClick(View v) {
setContentView(R.layout.level);
if(lvl.equals("1")) {
lvl1.setChecked(true);
}
if(lvl.equals("2")) {
lvl2.setChecked(true);
}
if(lvl.equals("3")) {
lvl3.setChecked(true);
}
if(lvl.equals("4")) {
lvl4.setChecked(true);
}
if(lvl.equals("5")) {
lvl5.setChecked(true);
}
}
protected void playOnClick(View v) {
setContentView(R.layout.play);
setQuestion();
}
private String getLevel() {
String FILENAME = "think_level";
FileInputStream fis;
byte[] buffer = new byte[1000];
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
setLevel("1");
return "-1";
}
try {
fis.read(buffer,0,1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String level = buffer.toString();
return level;
}
private void setLevel(String _level) {
String FILENAME = "think_level";
String level = _level;
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(level.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setQuestion() {
}
}
Here are my xml files:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="#+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/imageView1" android:src="#drawable/think" android:scaleType="fitCenter"></ImageView>
<Button android:id="#+id/play" android:text="Play" android:layout_height="wrap_content" android:layout_width="wrap_content" ></Button>
<Button android:text="Level" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/level"></Button>
</TableLayout>
Here is my level.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="#+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow android:id="#+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text="Level:" android:id="#+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</TableRow>
<TableRow android:id="#+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content">
<RadioGroup android:id="#+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<RadioButton android:id="#+id/lvl1" android:text="Level 1" android:layout_height="wrap_content" android:checked="true" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl2" android:text="Level 2" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl3" android:text="Level 3" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl4" android:text="Level 4" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl5" android:text="Level 5" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
</RadioGroup>
</TableRow>
<Button android:text="Set Level" android:id="#+id/updateLevel" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</TableLayout>
Here is play.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView android:id="#+id/scrollView1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text="TextView" android:id="#+id/question" android:layout_height="wrap_content" android:layout_width="wrap_content"></TextView>
</ScrollView>
<RadioGroup android:id="#+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" >
<RadioButton android:id="#+id/radioButton1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton>
<RadioButton android:id="#+id/radioButton2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton>
<RadioButton android:id="#+id/radioButton3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton>
</RadioGroup>
<Button android:id="#+id/go" android:text="Go" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
<Button android:id="#+id/tomenu" android:text="Back To Menu" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
</TableLayout>
The problem is that the view you are adding does not have a parent and therefore is not able to receive click events. Currently you're inflating the view using
View playv = inflater.inflate(R.layout.level, null);
You'll want to place a parent view in that second argument.
View playv = inflater.inflate(R.layout.level, parentView, false);
This will allow you to use a parent view but not actually attach it.
So the buttons are in your level and play layouts, and you're inflating those layouts, but it doesn't look like you're ever adding the layouts to the your main view/layout. Are you actually able to see those two layouts you are inflating?
inflation is async method, can you try to add the click listener after its inflated
//only inflate in oncreate / onresume
inflater.inflate(
R.layout.play, // resource
this, // root
true); //attach to root
//overide onFinishInflate and get the view here
protected void onFinishInflate() {
super.onFinishInflate();
Button gotomenu = (Button) levelv.findViewById(R.id.tomenu);
gotomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toMenuOnClick(v);
}
});
}
There is no apparent reason why this should not work.
Any runtime created views must be added to your linearlayout(or any other parent layout)
using :
linearLayoutMain.addView(updateLevel);
Have you used this buttons in any of the linear layouts in your xml file i.e. does these buttons appear when you reach the corresponding activity?
You should be seeing the exception at tbl.addView(updateLevel);, because you are trying to add a view whose parent is already specified.
Are you not seeing this exception ?
If You want item value on item click just use .setTag(some value); and getTag();
RelativeLayout firstContactRlayout = (RelativeLayout) myLayout.findViewById(R.id.firstContactRlayout);
firstContactRlayout.setTag(number);
firstContactRlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String gettags = (String) v.getTag();
Log.e("gettags", "--" + gettags);
}
});
Try this after tbl.addView(updateLevel); 0 of tbl.getChildAt(0) may change:
tbl.getChildAt(0).findViewById(R.id.updateLevel).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
updateLevelOnClick(v);
}
});

Categories