I am developing an application only to validate the interaction between activities through intents.
I created 5 ImageButton with an image for each. Each button is a movie and if you click any of them, is directed to a new activity with the synopsis of the film. The activity with the synopsis, there is an "up navigation" that returns the MainActivity (home).
The way I developed left very extensive project since created six activities (main activity and 5 activities, one for each film) and 6 layouts. Also, my apk is to 1.5mb.
Could someone help me with suggestions for best practices for I minimize my code or how developed is correct and could be developed in a real application?
I appreciate!!!
My MainActivity
package luizugliano.com.br.appfilmes;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void onClickBtVideo01(View view){
Intent intent = new Intent(getContext(),ActivityVideo01.class);
startActivity(intent);
}
public void onClickBtVideo02(View view){
Intent intent = new Intent(getContext(),ActivityVideo02.class);
startActivity(intent);
}
public void onClickBtVideo03(View view){
Intent intent = new Intent(getContext(),ActivityVideo03.class);
startActivity(intent);
}
public void onClickBtVideo04(View view){
Intent intent = new Intent(getContext(),ActivityVideo04.class);
startActivity(intent);
}
public void onClickBtVideo05(View view){
Intent intent = new Intent(getContext(),ActivityVideo05.class);
startActivity(intent);
}
private Context getContext(){
return this;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My ActivityVideo01 (other activities have the same code so I only put this as an example)
package luizugliano.com.br.appfilmes;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class ActivityVideo01 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_video01);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
//O método finish encerrará essa activity
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
My content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView android:text="Sinopse - Filmes" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="22dp"/>
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/layout_marginTop">
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton01"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:background="#drawable/btn_img_01"
android:onClick="onClickBtVideo01"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton02"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_02"
android:onClick="onClickBtVideo02"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton03"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_03"
android:onClick="onClickBtVideo03"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton04"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_04"
android:onClick="onClickBtVideo04"/>
<ImageButton
android:layout_width="#dimen/layout_width"
android:layout_height="#dimen/layout_height"
android:id="#+id/imageButton05"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/layout_marginLeft"
android:background="#drawable/btn_img_05"
android:onClick="onClickBtVideo05"/>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
My content_activity_video01.xml (other layout have the same code so I only put this as an example)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_activity_video01"
tools:context="luizugliano.com.br.appfilmes.ActivityVideo01">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Title Synopsis"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Synopsis"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_marginTop="51dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I suggest, that you have two activities, and both these activities will act as container activity for their respective fragments.
In your first activity's fragment have your buttons. In your second activity's fragment, play your movie.
Now when you click on the button, go from first activity's fragment to second activity's fragment. Use interfaces to communicate between your fragments.
This is the way i thought about it, if you have a better way please do share.
Instead Of taking five different activity just take single activity and replace textview's value dynamically on the click of your button.
Just marge the two xml file like that in content_main.xml create another relative layout(which is initially gone view) with height width match parent under the image button linear layout. When one image button is pressed then just gone the view of linear layout of image buttons and visible the textview relative layout and visible the back button of the up navigation. When user pressed the up navigation just gone the textview relative layout, gone the up navigation and visible the linear layout of image button.
you need not to create multiple activities to show synopsis from different films.
you need to create your synopsis activity like a template and pass information about selected film in intent.
now you can change the content of your activity depending upon the information you received from intent.
Basically, whenever you are copying the code you need to ask yourself do you really need to copy the code? almost all the time answer is NO and what you actually need to do is, think of ways you can reuse the code you are copying.
Implement onclicklisstener and use switch case to detect which button has been clicked, Use only one activity to display synopsis instead of four and use bundle along with Intent to send which synopsis has to be shown. Here is the code.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
case R.id.imageButton01:
//handle click for imgbutton1;
Intent intent = new Intent(getContext(),ActivityVideo.class);
//send which video should be played along with the intent. use bundle in ActivityVideo class to get this value.
intent.putExtra("Video name", "video1");
startActivity(intent);
case R.id.imageButton02:
//handle click for imgbutton2;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video2");
startActivity(intent);
case R.id.imageButton03:
//handle click for imgbutton3;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video3");
startActivity(intent);
case R.id.imageButton04:
//handle click for imgbutton4;
Intent intent = new Intent(getContext(),ActivityVideo.class);
intent.putExtra("Video name", "video4");
startActivity(intent);
}
}
Use ActivityVideo class instid of ActivityVideo01, 02 ......
ActivityVideo.java ->
public class ActivityVideo01 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_video01);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle extras = intent.getExtras();
String VideoName = extras.getString("Video Name");
// VideoName will be having the sent value.
if(VideoName == "video1"){
//code for what do you want to do when imagebutton1 is clicked
}elseif(VideoName == "video2"){
//code for what do you want to do when imagebutton2 is clicked
}elseif(VideoName == "video3"){
//code for what do you want to do when imagebutton3 is clicked
}elseif(VideoName == "video4"){
//code for what do you want to do when imagebutton4 is clicked
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
//O método finish encerrará essa activity
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hope it helps!
Related
Im developing a contacts app, and for now Ive been trying to get this drawables from the array get uploaded into the Gridview on the main screen AFTER the save mosaic button is clicked in the mosaic creation screen.
the floating action button (red plus button) on the mosaicListScreen (main screen) leads to the MosaicCreationScreen). the user hypothetically uploads the image and enters the mosaic name then saves using the save mosaic button, as can be seen in the image here
For now, before I focus on uploading image and letting the user create their own unique mosaics (groups), Im testing the Gridview updating with some drawables, which are listed in the array as can be seen in the code below.
The issue thats occuring is as soon as the user clicks the floating action button on the main screen, it updates the gridview with the drawables listed in the array of the MosaicCreation Screen, THEN it goes to the MosaicCreationScreen, and when save mosaic button is clicked on the MosaicCreationScreen, the intent goes to the main screen as its supposed to do, except the gridview will have nothing on it.
so its like its doing the opposite of whats supposed to happen in steps.
here is my code for the two screens:
public class mosaicsListScreen extends AppCompatActivity {
public static mosaicsListScreen theScreen; //this variable is used in the MosaicCreationScreen to point to this screen to find the GridView by id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = this;
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
}
}
here is the code for the MosaicCreationScreen (the one that opens after user clicks floating action button from mosaicListScreen (main screen))
public class MosaicCreationScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaic_creation_screen);
final GridView mosaicList = (GridView) mosaicsListScreen.theScreen.findViewById(R.id.mosaicList);
mosaicList.setAdapter(new ImageAdapter(this)); //this line of code displays the mosaics on mosaicListScreen
Button saveNewMosaicButton = (Button) findViewById(R.id.saveNewMosaicButton);
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
//mThumbIds.notify();
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
startActivity(intent);
finish();
//mosaicList.setAdapter(new ImageAdapter(this)); //this displays the mosaics on mosaicListScreen, it logically should go here, however "this" causes an error saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)
Toast.makeText(mosaicsListScreen.theScreen, "Mosaic Created!", Toast.LENGTH_SHORT).show();
}
});
/* mosaicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(mosaicsListScreen.theScreen, "", Toast.LENGTH_SHORT).show();
}
});*/
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
//this array holds the drawables that would appear on the Gridview
private Integer[] mThumbIds = {
R.drawable.family,
R.drawable.project
};
}
}
Here are the XML for the layouts:
content_mosaics_list_screen.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="codesages.mosaic.mosaicsListScreen"
tools:showIn="#layout/activity_mosaics_list_screen">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/create_a_mosaic_or_pick_from_the_mosaics_created"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deleteMosaicButton"
android:src="#android:drawable/ic_menu_delete"
android:clickable="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:contentDescription="" />
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/mosaicList"
android:layout_above="#+id/textView7"
android:numColumns="auto_fit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/holdMosaictoDeleteLabel"
android:id="#+id/textView7"
android:layout_marginBottom="16dp"
android:layout_above="#+id/deleteMosaicButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="codesages.mosaic.mosaicsListScreen">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/createMosaicButton"
android:layout_width="56dp"
android:layout_height="66dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add" />
<include layout="#layout/content_mosaics_list_screen" />
</android.support.design.widget.CoordinatorLayout>
activity_mosaic_creation_screen.xml
<?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: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"
tools:context="codesages.mosaic.MosaicCreationScreen"
android:focusable="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mosaicNametextField"
android:hint="Mosaic Name"
android:layout_marginTop="81dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save New Mosaic"
android:id="#+id/saveNewMosaicButton"
android:layout_marginTop="48dp"
android:layout_below="#+id/uploadMosaicImageButton"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Mosaic Image"
android:id="#+id/uploadMosaicImageButton"
android:layout_marginTop="68dp"
android:layout_below="#+id/mosaicNametextField"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
</RelativeLayout>
mosaicList.setAdapter(new ImageAdapter(this));
thats what appears to be creating the mosaics. if i comment this out, i wont see anything in the gridview.
however, i believe that should be inside the saveNewMosaicButton onClick, but I am getting an error that says "saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)"
HERE is an image example of what the desired result should be. however whats happening right now is as ive stated, as soon as the floating action button is clicked, the mosaics are created, THEN it takes you to the creation screen, in which wehn i click save mosaics, it actually erases the mosaics...a job of the trash icon which is too soon to function for now heh.
appreciate help on this
Currently, you have
public static mosaicsListScreen theScreen;
in your first Activity which you use to fill the ListView in this first Activity. This is a dangerous approach because the Activity instance referenced by this variable may be destroyed, for example if you're doing work in your second Activity (e.g. downloading images) which uses much memory, but also if the user somehow triggers a configuration change.
As you are calling finish() after starting the second Activity, you even tell the system that the first Activity may be destroyed. The only reason you did not get a NPE is that the system destroys the finished Activity not instantly but as soon as it seems a good idea to do so.
All in all, you need a way to safely transmit information from one Activity to the other. In your case, I think you would like to send the Uri of the selected images ( or for now, send the resource id of the selected drawables). Both can be accomplished by using Intent extras.
Basically, there are two options:
use startActivityForResult() and override onActivityResult() to obtain the desired information for the first Activity
simply start the first Activity from the second Activity once you have the result and use getIntent() in the first Activity (e.g. in onCreate()) to check for results
No matter what you do, always access UI elements like the ListView in the Activity to which they belong!
If you choose the second option, your first Activity could look like this:
public class mosaicsListScreen extends AppCompatActivity {
public static final String THUMB_IDS = "someuniquestring";
private GridView mosaicList;
private ArrayList<Integer> mThumbIds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
fillThumbIds();
mosaicList = (GridView) findViewById(R.id.mosaicList);
// Note: Adapter code in this Activity
mosaicList.setAdapter(new ImageAdapter(this));
}
private void fillThumbIds()
{
mThumbIds = new ArrayList();
// somehow get older thumb ids if necessary (from database?)
// and add to ArrayList like this:
mThumbIds.add(R.drawable.family);
mThumbIds.add(R.drawable.project);
// assuming we transmit resource id's: use an int array with the Intent
int[] newThumbIds = getIntent().getIntArrayExtra(THUMB_IDS);
if (newThumbIds != null)
{
// loop through the array to add new thumb ids
for (int i = 0; i < newThumbIds.length; i++) {
mThumbIds.add(newThumbIds[i]);
}
}
}
// Adapter code goes here
// Note: thumbIds no longer as array but as ArrayList!
}
In the second Activity, you put the selected thumb ids as Intent extra as follows:
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
// if 'myNewThumbs' is the int array with the new thumb ids
intent.putExtra(mosaicsListScreen.THUMB_IDS, myNewThumbs);
startActivity(intent);
finish();
}
});
I’m working on a project in which I have to do a shared transition.
I want to perform a transition on an ImageView from my splash Activity [First Activity] to Login Activity [Second Activity] which has the ImageView in a Fragment. The Image in my 1st Activity and The Image in the fragment of my 2nd Activity are same and Shares The Same Transition Name. I’m unable to perform the transition.
My Splash Activity Code is This
public class Splash extends Activity implements View.OnClickListener{
private ImageView imageView;
private String SharedElementname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getWindow().setExitTransition(R.transition.shared_element_transition_a);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setSharedElementExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition_a));
}
setContentView(R.layout.activity_splash);
imageView = (ImageView)findViewById(R.id.splashimage);
SharedElementname = getString(R.string.sharedname);
imageView.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_splash, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(this,v,SharedElementname);
Intent intent = new Intent(this, LoginActivity.class);
ActivityCompat.startActivity(this, intent, compat.toBundle());
}
My Login Activity Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(BuildConfig.MINT_API_ENABLED) {
Mint.initAndStartSession(LoginActivity.this, BuildConfig.MINT_API_KEY);
}
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition_a));
}
setContentView(R.layout.activity_login);
}
Some More Codes….
*****************************************************************************
My Fragment Code Within Login Activty
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loginTab = new LoginTab();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementReturnTransition(TransitionInflater.from(
getActivity()).inflateTransition(R.transition.shared_element_transition_a));
setExitTransition(TransitionInflater.from(
getActivity()).inflateTransition(android.R.transition.fade));
loginTab.setSharedElementEnterTransition(TransitionInflater.from(
getActivity()).inflateTransition(R.transition.shared_element_transition_a));
loginTab.setEnterTransition(TransitionInflater.from(
getActivity()).inflateTransition(android.R.transition.fade));
}
}
Some More Codes….
*************************************************************************************
My Splash Activity XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_new"
android:orientation="vertical"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:id="#+id/SplashLayout"
>
<ImageView
android:id="#+id/splashimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#drawable/eventifyd_logo"
android:transitionName="#string/sharedname"
/>
</RelativeLayout>
</LinearLayout>
My Transition XML File [Shared_element_transition]
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android" android:duration="5000">
<changeTransform />
<changeBounds />
<!—
I also tied ChangeImageTranform But Nothing Happened
-->
</transitionSet>
My Fragment XML File
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
>
<ImageView
android:id="#+id/profile_pic_login"
android:layout_above="#+id/login_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#drawable/eventifyd_logo"
android:transitionName="#string/sharedname"
/>
<TextView
android:layout_marginTop="30dp"
android:id="#+id/login_text"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/login_text"
style="#style/thin.white.large"/>
</RelativeLayout>
</LinearLayout>
I couldn't do it the way i was try. I changed the Fragments to Activity and it worked as a charm. I think Making transition from Activity to a Fragment of another activity is not Possible. Anyway, My this approach worked.
I have to make a program where what I write in EditText shows up in TextView when I press a button. However when I press the button, the app shuts down. Where am I going wrong? I have tried doing it the way many similar questions' solutions said, but to no use. Please help. PS: I'm a total noob at android programming. Any help would be appreciated.
This is my main class:
public class abc extends Activity implements View.OnClickListener {
EditText editText;
TextView textView;
Button button;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_abc);
EditText editText=(EditText)findViewById(R.id.ed_edit);
TextView textView=(TextView)findViewById(R.id.text_tview);
Button button=(Button)findViewById(R.id.btn_button);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_abc, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_button:
name= editText.getText().toString();
textView.setText(name);
break;
}
}
}
This is the xml code:
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:text="ABD"
android:id="#+id/text_tview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
<Button android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="HERE"
android:id="#+id/btn_button"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ed_edit"/>
</LinearLayout>
You are initializing local variables using findViewById().
Replace :
EditText editText=(EditText)findViewById(R.id.ed_edit);
TextView textView=(TextView)findViewById(R.id.text_tview);
Button button=(Button)findViewById(R.id.btn_button);
With :
editText=(EditText)findViewById(R.id.ed_edit);
textView=(TextView)findViewById(R.id.text_tview);
button=(Button)findViewById(R.id.btn_button);
I'm a beginner to android programming and I'm trying make a simple Rock, Paper, Scissors app. Right now I have three buttons (rock, paper, and scissors). When the user presses them, the computer randomly picks rock, paper, or scissors and then compares them to see if the user won. If the user won, then I want the score counter to in the upper right corner of the screen to increment by 1. At first I tried to initialize int scoreCount outside of the onCreate method which resulted in the app not being able to start up. Right now, I'm getting a null pointer exception inside my upScore method where I'm trying to use setText to update my TextView with the newest scoreCount. Below is my code. Thanks for any help that you can provide! Let me know if you need additional info! I'm really stuck on this!
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int scoreCount;
TextView scoreView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreCount = 0;
TextView scoreView = (TextView) findViewById(R.id.score);
scoreView.setText("Score: " + scoreCount);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void outcome(View view){
//This function will determine whether the user picked Rock, Paper, or Scissors
//and then randomly have the computer pick Rock, Paper, or Scissors. A dialog will then
//generate to let the user know whether they won or lost.
String[] rpsArray = {"Rock","Paper","Scissors"};
int index = new Random().nextInt(rpsArray.length);
String cpuChoice = rpsArray[index];
String message = "";
int id = view.getId();
switch(id){
case R.id.rock_button:
if(cpuChoice.equals("Rock")){
//Tie
message = "The Computer picked Rock! It's a Tie!";
}
else if(cpuChoice.equals("Paper")){
//You Lose
message = "The Computer picked Paper! You Lose!";
}
else if(cpuChoice.equals("Scissors")){
//You win
message = "The Computer picked Scissors! You Win!";
upScore();
}
break;
case R.id.paper_button:
if(cpuChoice.equals("Paper")){
//Tie
message = "The Computer picked Paper! It's a Tie!";
}
else if(cpuChoice.equals("Scissors")){
//You Lose
message = "The Computer picked Scissors! You Lose!";
}
else if(cpuChoice.equals("Rock")){
//You win
message = "The Computer picked Rock! You Win!";
upScore();
}
break;
case R.id.scissors_button:
if(cpuChoice.equals("Scissors")){
//Tie
message = "The Computer picked Scissors! It's a Tie!";
}
else if(cpuChoice.equals("Rock")){
//You Lose
message = "The Computer picked Rock! You Lose!";
}
else if(cpuChoice.equals("Paper")){
//You win
message = "The Computer picked Paper! You Win!";
upScore();
}
break;
}
DialogFragment dialog = WinOrLoseDialog.newInstance(message);
dialog.show(getFragmentManager(),"WinOrLose");
}
public void upScore(){
scoreCount++;
scoreView.setText("Score: " + scoreCount);
}
}
Here's my xml layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#color/dark_teal">
<Button
android:id="#+id/rock_button"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="#string/rock"
android:onClick="outcome" />
<Button
android:id="#+id/paper_button"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_below="#id/rock_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/paper"
android:onClick="outcome" />
<Button
android:id="#+id/scissors_button"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_below="#id/paper_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/scissors"
android:onClick="outcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/version"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/white" />
<TextView
android:id="#+id/score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#color/white"
android:textSize="25sp"
android:textStyle="bold" />
</RelativeLayout>
This line in onCreate() is causing all your trouble:
TextView scoreView = (TextView) findViewById(R.id.score);
Instead of initializing the property of your activity class, you are creating and initializing a local variable. Change this to:
this.scoreView = (TextVoew) findViewById(R.id.score);
I'm very new to programming in Android, but have been struggling all day with a problem and would appreciate your help.
I'm trying to create a form to get user information (essentially a new contact) which is accessed from the menu. When I click the button to create the new form, I get the following error:
"Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#626fd5e0"
This is my code:
The menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/search"
android:title="#string/settings_search"
android:alphabeticShortcut="#string/settings_shortcut_search" />
<item android:id="#+id/new_contact"
android:title="#string/settings_new"
android:alphabeticShortcut="#string/settings_shortcut_new" />
</menu>
The code for calling the new activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_contact:
//activities to create a new account
//startActivity(new Intent(this, Prefs.class));
Intent i = new Intent(MainActivity.this, NewContact.class);
startActivity(i);
//addSaver("String");
return true;
case R.id.search:
return true;
// More items go here (if any) ...
}
return false;
}
The view for the new contact activity:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">"
<LinearLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="top">
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is a test\nsecond line\n"/>
<Button
android:id="#+id/new_contact_button"
android:layout_height="wrap_content"
android:text="#string/submit" />
</LinearLayout>
</ScrollView>
And the code for the new activity:
public class NewContact extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_contact);
// Set up click listeners for all the buttons
View newContactButton = findViewById(R.id.new_contact_button);
newContactButton.setOnClickListener(this);
}
Bizarrely if I comment out the button from the class and from the xml then it works correctly and opens up the new activity (but of course I can't do anything with that activity).
In your button xml code, you are missing
android:layout_width="wrap_content"
add that and give it a shot.